<?php

namespace app\mos\controller;

use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardLeaduser;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardQrcode;
use app\common\model\CardRankUserLog;
use app\common\model\CardStore;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\validate\LoginUsers;
use app\index\controller\Wxcard;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardusertest extends Mobilebase
{

    /*
     * 首页
     * $card_id
     *
     */
    public function index()
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $info = $this->getuserinfo($arr);
        //不存在符合条件的则跳转到投放页面
        if (empty($info)) {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        } else {
            $CardUserGet = new CardUserGet();
            $info['balance'] = sprintf("%.2f", $info['balance']);
            $maps['card_id'] = $arr['card_id'];
            if ($info['qrcode'] == ''){
                $userinfo['qrcode'] = $this->qrcode($info['code']);
                $CardUserGet->save($userinfo,['id'=>$info['id']]);
            }
            $CardMember = new CardMember();
            $card = $CardMember->where($maps)->find();
            $this->assign('card', $card);       //ka
            $this->assign('info', $info);       //user
            $jssdk['type'] = 0;
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //信息同步
    /*
     *
     *  card_id  phone  old_code
     *
     */
    public function synusers(Request $request){
        $param = $request->param();
        $this->_init();
        $appid = $this->getappid($param['card_id']);
        $user['openid'] = Session::get($appid.'_openid');
        $CardLeaduser = new CardLeaduser();
        $CardUserGet = new CardUserGet();
        $CardMember = new CardMember();
        $card = $CardMember->where(['card_id'=>$param['card_id']])->field('card_id,syn_is_exist')->find();
        if ($request->isAjax()){
            $params = $request->post();
            $user = $CardUserGet->where(['card_id'=>$params['card_id'],'openid'=>$user['openid']])->field('id,c_id,phone,old_code,mid,openid,card_id,is_syn,code')->find();
            if ($card['syn_is_exist'] == '1'){
                $user['phone'] = $params['phone'];          //手机号
            }else{
                $user['old_code'] = $params['old_code'];    //旧卡号
            }
            $res = $this->synuserrec($user,$card);
            return json($res);
        }else{
            $user = $CardUserGet->where(['card_id'=>$param['card_id'],'openid'=>$user['openid']])->field('c_id,phone,old_code,code,nickname,bonus,balance,mid,openid,code,card_id,is_syn')->find();
           $syninfo = $CardLeaduser->where(['new_code'=>$user['code'],'statu'=>1])->find();
           if ($syninfo){
               $syninfo['nickname'] = $user['nickname'];
               $syninfo['card_id'] = $user['card_id'];
               $this->assign('user', $syninfo);
               return $this->fetch('synend');
           }else {
               if ((int)$card['syn_is_exist'] !== 0) {
                   $this->assign('card', $card);
                   if ($user['is_syn'] == 1) {
                       $this->assign('user', $user);
                       return $this->fetch('synend');
                   } else {
                       return $this->fetch();
                   }
               } else {
                   return $this->fetch('synend');
               }
           }
        }

    }

    public function lotlogin(){
        Session::clear();
    }


    //同步业务
    /*
     * c_id  phone  old_code  mid  openid  card_id
     *
     */
    public function synuserrec($param,$card){

        //同步会员数据
        //判断同步
        $CardMember = new CardMember();
        if ($card['syn_is_exist'] == '1' || $card['syn_is_exist'] == '2') {
            $CardLeaduser = new CardLeaduser();
            //手机号为条件
            if ($card['syn_is_exist'] == '1') {
                $synuser = $CardLeaduser->where(['phone' => $param['phone'], 'mid' => $param['mid']])->find();
                //是否已被同步
                if ($synuser['statu'] == '1') {
                    $rarr['code'] = 1;
                    $rarr['massage'] = '请同步自己的会员卡';
                    return $rarr;
                }
            } else {
                //旧卡号为条件
                $synuser = $CardLeaduser->where(['old_code' => $param['old_code'], 'mid' =>$param['mid']])->find();
                //是否已被同步
                if ($synuser['statu'] == '1') {
                    $rarr['code'] = 1;
                    $rarr['massage'] = '请同步自己的会员卡';
                    return $rarr;
                }
            }
            if (isset($synuser) && $synuser['statu'] == '0') {
                //转入WxCard类执行
                $sdata = [
                    'code' => $param['code'],
                    'card_id' => $param['card_id'],
                    'bonus' => $synuser['bonus'],
                    'balance' => $synuser['balance'],
                    'openid' => $param['openid'],
                    'record_bonus' => '同步奖励',
                ];
                $Wxcard = new Wxcard();
                $Wxcard->synbonus($sdata);
                $Wxcard->synbalance($sdata);
                //END
                //存入核销表
                $cdata['card_id'] = $param['card_id'];
                $cdata['code'] = $param['code'];
                $cdata['add_bonus'] = $sdata['bonus'];
                $cdata['add_balance'] = $sdata['balance'];
                $cdata['openid'] = $param['openid'];
                $cdata['mid'] = $param['mid'];
                $cdata['con_username'] = 'SYNCGIFT';
                $cdata['record_balance'] = '同步';
                $cdata['record_bonus'] = $sdata['record_bonus'];
                $cdata['hx_fs'] = 23;
                $cdata['create_time'] = time();
                $CardUserUpdate = new CardUserUpdate();
                $CardUserUpdate->allowField(true)->save($cdata);
                //END
                //更新导入会员表
                $ldata['statu'] = 1;
                $ldata['update_time'] = time();
                $ldata['new_code'] = $param['code'];
                $wherel['id'] = $synuser['id'];
                $CardLeaduser->allowField(true)->save($ldata, $wherel);
                $rarr['code'] = 0;
                $rarr['massage'] = '同步成功';
            } else {
                $rarr['code'] = 3;
                $rarr['massage'] = '同步条件不满足';
               //同步条件不满足
            }
        }else{
            $rarr['code'] = 4;
            $rarr['massage'] = '未开启同步';
//            $rarr['massage'] = json_encode($card,JSON_UNESCAPED_UNICODE);
                  //未开启同步
        }
        return $rarr;
    }


    //在线充值
    /* 查询该会员卡的信息支付时用作传入参数
     *
     */
    public function recharge()
    {

        $appid = $this->getappid(request()->param('card_id'));
        if (Request()->isAjax()) {
            $arr = request()->param();
//            return json($arr);
            if ($this->getpaystatu($arr) == 1) {
                if (Request()->post('price') > 0) {
                    $Merchant = new Merchant();
                    $Agent = new Agent();
                    $WxOpen = new WxOpen();
                    $map['id'] = Request()->post('mid');
                    $config = $Merchant->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                    $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

                    $options = array(
                        'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                        'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                        'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                    );
//                return json($options);
                    $weObj = new Wxobjopen($options);
                    $price = request()->post('price');
                    $appid = $users['authorizer_appid'];
                    $mch_id = $agent['partnerid'];
                    $out_trade_no = request()->post('orderid');
                    $body = "会员卡充值";
                    $sub_mch_id = $config['sub_mch_id'];
                    $sub_appid = $userwx['authorizer_appid'];
//                    $sub_mch_id = '';
                    $total_fee = $price * 100;
                    $data['orderid'] = $out_trade_no;
                    $data['mid'] = request()->post('outer_mid');
                    $data['openid'] = request()->post('openid');
                    $data['pay_statu'] = 0;
                    $data['pay_cate'] = 'recharge';
                    $data['price'] = $price;
                    $data['yf_price'] = $price;
                    $data['zk_price'] = $data['yf_price'] - $data['price'];
                    $data['add_time'] = time();
                    $data['attach'] = 'cardcz';
                    $data['cz_card_id'] = request()->post('cardid');
                    $CardCzLog = new CardCzLog();
                    $CardCzgive = new CardCzgive();
                    $giveid = request()->post('giveid');
                    $czdata['openid'] = request()->post('openid');
                    $czdata['card_get_id'] = $data['cz_card_id'];
                    $czdata['code'] = getcardcode_getid($data['cz_card_id']);
                    $czdata['cz_price'] = $price;
                    $czdata['zs_price'] = $CardCzgive->where('id', $giveid)->value('zs_money');
                    $czdata['orderid'] = $out_trade_no;
                    $czdata['giveid'] = $giveid;
                    $czdata['addtime'] = time();
                    $czdata['remark'] =request()->post('remark');
                    $c = $CardCzLog->allowField(true)->save($czdata);
                    $Paylog = new Paylog();
                    $add = $Paylog->allowField(true)->save($data);
                    $sub_openid = request()->post('openid');
                    $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                    $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                    $nonce_str = $weObj->generateNonceStr();
                    $partnerkey = $options['partnerkey'];
                    $arrdata = array(
                        "appid" => $appid,
                        'sub_appid' => $sub_appid,
                        "mch_id" => $mch_id,
                        "sub_mch_id" => $sub_mch_id,
                        "nonce_str" => $nonce_str,
                        "body" => $body,
                        "out_trade_no" => $out_trade_no,
                        "total_fee" => $total_fee,
                        "spbill_create_ip" => $spbill_create_ip,
                        "notify_url" => $notify_url,
                        "sub_openid" => $sub_openid,
                        'trade_type' => 'JSAPI'
                    );

//                    $arrdata = array(
//                        "appid" => $appid,
//                        "mch_id" => $mch_id,
//                        "nonce_str" => $nonce_str,
//                        "body" => $body,
//                        "out_trade_no" => $out_trade_no,
//                        "total_fee" => $total_fee,
//                        "spbill_create_ip" => $spbill_create_ip,
//                        "notify_url" => $notify_url,
//                        "trade_type" => "APP",
//                    );
                    $pay_xml = $weObj->createWxPackageXmls($arrdata,$partnerkey);
//                    $pay_xml = $weObj->createWxPackageXmls($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, '', $sub_openid);
                    $pay_xml = $weObj->get_pay_id($pay_xml);
                    if ($pay_xml['return_code'] == 'SUCCESS') {
                        $prepay_id = $pay_xml['prepay_id'];
                        $jsApiObj["appId"] = $appid;
                        $timeStamp = time();
                        $jsApiObj["timeStamp"] = "$timeStamp";
                        $jsApiObj["nonceStr"] = $nonce_str;
                        $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                        $jsApiObj["signType"] = "MD5";
                        $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                        //状态码
                        $jsApiObj['code'] = 0;
                    } else {
                        $jsApiObj = ['code' => 9002, 'message' => $pay_xml['return_msg']];
                    }
                } else {
                    $jsApiObj = ['code' => 9001, 'message' => '请输入正确的充值金额！'];
                }
            }else{
                $jsApiObj = ['code' => 9003, 'message' => '充值失败！'];
            }
            return json($jsApiObj);
        } else {

            //获取传值
            $arr = request()->param();
            //解密code 获取用户信息
            if (isset($arr['encrypt_code'])){
                $this->getusercode($arr);
            }
            //获取授权
            $this->_init();
            $info = $this->getuserinfo($arr);
            //不存在符合条件的则跳转到投放页面
            if (empty($info)) {
                $data['card_id'] = $arr['card_id'];
                $data['openid'] = Session::get($appid.'_openid');
                $this->redirect('Carduser/addcard', $data);
            } else {
                $Merchant = new Merchant();
                $CardMember = new CardMember();
                $CardCzgive = new CardCzgive();
                $maps['card_id'] = $arr['card_id'];
                $maps['statu'] = 1;
                $czgive = $CardCzgive->where($maps)->select();
                $user['mid'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
                $user['openid'] = Session::get($appid.'_openid');
                $card = $CardMember->where(['card_id'=>$arr['card_id']])->field('title,is_cz_qtprice,is_rec_remark,top_mid,mid')->find();
                if ($czgive){
                    $card['is_recharge'] = 1;
                }else{
                    $card['is_recharge'] = 0;
                }
                //END
                $sqlmach['top_mid'] = $card['top_mid'];
                $sqlmach['sub_mch_id'] = ['neq',''];
                $machlist = $Merchant->where($sqlmach)->field('id,merchant')->select();
                $card['merchant'] = $Merchant->where('id',$card['mid'])->value('merchant');
                $this->assign('machlist',$machlist);
                $this->assign('card',$card);
                $this->assign('user', $user);
                $this->assign('czgive', $czgive);
                $this->assign('info', $info);
                $CardMember = new CardMember();
                $is_zxcz = $CardMember->where('card_id', $arr['card_id'])->value('is_zxcz');
                if ($is_zxcz == 1) {
                    return $this->fetch();
                } else {
                    return $this->fetch('off');
                }
            }
        }
    }



    //检查支付提交
    private function getpaystatu($arr){
        //自定义
        if ($arr['giveid'] == ''){
            if ($arr['givetype'] == 'custom'){
                $res = 1;
            }else{
                $res = 2;
            }
        }else{
            //规则充值
            if ($arr['givetype'] == 'giverule'){
                $res = 1;
            }else{
                $res = 2;
            }
        }
        return $res;
    }

    /*
     * 支付结束
     *
     */
    public function r_payover()
    {
        if (request()->isAjax()) {
            $request = request();
            $param = $request->post();


            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $param['id'];
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );

            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no =$param['orderid'];
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);

       //     $orderno = $payorder_xml['transaction_id'];
            $pay_zt = $payorder_xml['trade_state'];

            if ($pay_zt == "SUCCESS") {
                $CardExt = new Cardextend();
                 $url = $CardExt->chackputurl($out_trade_no);
                $rarr = ['code' => 0, 'message' => "充值成功",'url'=>$url];
            } else {
                $rarr = ['code' => 1, 'message' => "充值失败"];
            }
            return json($rarr);

        }
    }

    //获取订单
    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }


    //余额    查询该会员卡余额
    /*
     * $card_id
     *
     */
    public function balance($card_id='')
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        $appid = $this->getappid($arr['card_id']);
        if ($info) {
            $arr = request()->param();
            $mab['openid'] = Session::get($appid.'_openid');
            $mab['card_id'] = $info['card_id'];
            $mab['add_balance|del_balance']= ['neq', 0];
            $CardUserUpdate = new CardUserUpdate();
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();

            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get($appid.'_openid');
            $maps['have'] = 1;
            $card['balance'] = $info['balance'];
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_money = $CardMember->where('card_id', $arr['card_id'])->value('is_money');
            if ($is_money == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        }
    }

    //余额详情
    public function balancedetail(){
        $arr = request()->param();
        $map['id'] = $arr['dalanceid'];
        $map['card_id'] = $arr['card_id'];
        $map['add_balance|del_balance']= ['neq', 0];
        $CardUserUpdate = new CardUserUpdate();
        $info = $CardUserUpdate->where($map)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //积分    查询该会员卡积分
    /*
     * $card_id
     */
    public function bonus($card_id = '')
    {
        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $info = $this->getuserinfo($arr);
        if ($info) {
            $arr = request()->param();
            $mab['card_id'] = $arr['card_id'];
            $mab['openid'] = Session::get($appid.'_openid');
            $mab['add_bonus|del_bonus'] = array('neq', 0);
            $CardUserUpdate = new CardUserUpdate();
            $CardUserGet = new CardUserGet();
            $CardMember = new CardMember();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();
            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get($appid.'_openid');
            $card['bonus'] = $CardUserGet->where($maps)->value('bonus');
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_bonus = $CardMember->where('card_id', $arr['card_id'])->value('is_bonus');
            if ($is_bonus == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //余额
    //余额    查询该会员卡余额
    /*
     * $card_id
     *
     */
    public function balancelist($card_id='')
    {

        //获取传值
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $appid = $this->getappid($arr['card_id']);
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $arr = request()->param();
            $mab['openid'] =  Session::get($appid.'_openid');
            $mab['card_id'] = $info['card_id'];
            if ($arr['type'] == "recharge"){
                $mab['add_balance']= ['neq', 0];
            }elseif($arr['type'] == "consum"){
                $mab['del_balance']= ['neq', 0];
            }
            $CardUserUpdate = new CardUserUpdate();
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            $list = $CardUserUpdate->where($mab)->order('id desc')->select();
            $maps['card_id'] = $arr['card_id'];
            $maps['openid'] = Session::get($appid.'_openid');
            $maps['have'] = 1;
            $card['balance'] = $info['balance'];
            $card['brandname'] = $CardMember->where('card_id', $arr['card_id'])->value('brand_name');
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            $this->assign('card', $card);
            $this->assign('list', $list);
            $is_money = $CardMember->where('card_id', $arr['card_id'])->value('is_money');
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//            var_dump($url);
            if ($is_money == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $data['card_id'] = $arr['card_id'];
            $data['openid'] = Session::get($appid.'_openid');
            $this->redirect('Carduser/addcard', $data);
        }
    }

    //
    public function consumelist(Request $request){
        if ($request->isAjax()){
            $param = $request->post();
            $Paylog = new Paylog();
//            $map['card_id'] = $param['card_id'];
            $map['openid'] = $param['openid'];
            if ($param['type'] == 'wx_price') {
                $map['pay_statu'] = 1;
                $map['pay_fs'] = ['in', [0, 2]];
                $map['add_time'] = ['GT',strtotime('-3 month')];
                $list = $Paylog->where($map)->field('id,mid,pay_cate,pay_fs,pay_statu,price,add_time')->order('add_time', 'desc')->paginate(5);
                $count = $Paylog->where($map)->count();
                $lists = [];
                foreach ($list as $k=>$v){
                    $lists[$k] = $v;
                    $lists[$k]['pay_fs'] = getpayfs($v['pay_fs']);
                    $lists[$k]['merchant'] = getmachname($v['mid']);
                    $lists[$k]['add_time'] = date('Y-m-d h:i:s',$v['add_time']);
                    $lists[$k]['pay_statu'] = getpaystatus($v['pay_statu']);
                }
            }else{
                $CardUserFee = new CardUserFee();
//                $map['type'] = 2;
                $map['create_time'] = ['GT',strtotime('-3 month')];
                $map['card_id'] = $param['card_id'];
                $list = $CardUserFee->where($map)->field('id,mid,num as price,pay_cate,create_time as add_time,type')->order('create_time', 'desc')->paginate(5);
                $count = $CardUserFee->where($map)->count();
                $lists = [];
                foreach ($list as $k=>$v){
                    $lists[$k] = $v;
                    $lists[$k]['price'] = $v['type'] == 2?'-'.$v['price']:$v['price'];
                    $lists[$k]['pay_fs'] = '微信会员卡';
                    $lists[$k]['merchant'] = getmachname($v['mid']);
                    $lists[$k]['add_time'] = date('Y-m-d h:i:s',$v['add_time']);
                    $lists[$k]['pay_statu'] = '成功';
                }
            }
            $page_num = ceil($count / 5);

            if ($lists){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $lists;
                $data['conut'] = $count;
                $data['page_num'] = $page_num;
                $data['page'] = $param['page'];
            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
                $data['conut'] = $count;
                $data['page_num'] = $page_num;
                $data['page'] = $param['page'];
            }
            return json($data);
        }else{
            $this->_init();
            $param = $request->param();
            $user = $this->getuserinfo($param,1);
            $this->assign('user',$user);
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($param['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            return $this->fetch();
        }
    }

    //余额详情
    public function consumedetail(){
        $arr = request()->param();
        if ($arr['type'] == 'wx_balance') {
            $map['id'] = $arr['recordid'];
            $CardUserFee = new CardUserFee();
            $info = $CardUserFee->where($map)->field('mid,num,create_time as add_time,orderid,cate as pay_cate,source,action_user')->find();
            $info['pay_cate'] = getcate($info['pay_cate']);

        }elseif($arr['type'] == 'wx_price'){
            $map['id'] = $arr['recordid'];
            $Paylog = new Paylog();
            $info = $Paylog->where($map)->field('mid,price as num,add_time,orderid,pay_cate,source,d_cashier as action_user')->find();

        }
        $info['add_time'] = date('Y-m-d h:i:s',$info['add_time']);
        $this->assign('info',$info);
        return $this->fetch();
    }

    //等级
    /*
     * $card_id
     */
    public function level($card_id ='')
    {
        $CardRank = new CardRank();
        if (request()->isAjax()){
            $param = request()->post();

            $maps['card_id'] = $param['card_id'];

            $list = $CardRank->where($maps)->field('live_title as name,growup')->select();

            $count = count($list);

            $hasPay = $param['growup'];
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['count'] = $count;
                $data['hasPay'] =$hasPay;
            }else{
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['count'] = $count;
                $data['hasPay'] =$hasPay;

            }
            return json($data);
        }else {
            //获取传值
            $arr = request()->param();
            //解密code 获取用户信息
            if (isset($arr['encrypt_code'])) {
                $this->getusercode($arr);
            }
            //获取授权
            $this->_init();
            $appid = $this->getappid($arr['card_id']);
            $info = $this->getuserinfo($arr);
            if ($info) {


                //获取对应等级
                $maps['card_id'] = array('eq', $arr['card_id']);
                $level = $CardRank->where($maps)->select();
                //JSSDK
                $share['wxjssdk'] = $this->getsharejssdk($card_id);
                $share['wxjssdk'] = json_encode($share['wxjssdk']);
                $this->assign('share', $share);
                $this->assign('level', $level);
                $this->assign('info', $info);
                $CardMember = new CardMember();
                $is_rank = $CardMember->where('card_id', $card_id)->value('is_rank');
                if ($is_rank == 1) {
                    return $this->fetch();
                } else {
                    return $this->fetch('off');
                }
            } else {
                $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
            }
        }
    }

    //等级奖励领取
    /*
     * ajax 方式     gid  即该会员在数据表中的id
     * */
    public function getRankReward(){
        if (Request()->isAjax()){
            $arr = request()->post();      //获取参数
            $CardRank = new CardRank();
            $CardUserGet = new CardUserGet();
            $map['id'] = $arr['gid'];
            $user = $CardUserGet->where($map)->field('growup,bonus,openid,code,card_id,rank_lock,balance,c_id,id,nickname,top_mid,mid')->find();  //会员信息
            $isarr['lid'] = $arr['lid'];
            $isarr['user_growup'] = $user['growup'];
//            return $isarr;
            $is_rank = $this->is_rank_new($isarr);      //等级判断
            if ($is_rank == 0){
                $rank = $CardRank->where(['id'=>$arr['lid']])->find();     //等级奖励
//                $level = getlive($user['card_id'],$user['bonus']);  //是否已领取
                if ($user['rank_lock'] < $rank['live']){
                    if ($rank['reward_bonus'] > 0 || $rank['reward_balance'] >0 || $rank['zs_card_id_all'] !== '') {
                        $CardRankUserLog = new CardRankUserLog();
                        $data['c_id'] = $user['c_id'];
                        $data['us_c_id'] = $user['id'];
                        $data['level'] = $rank['live'];
                        $data['card_id'] = $user['card_id'];
                        $data['code'] = $user['code'];
                        $data['openid'] = $user['openid'];
                        $data['bonus'] = $rank['reward_bonus'];
                        $data['balance'] = $rank['reward_balance'];
                        $data['cards'] = json_encode($rank['zs_card_id_all']);
                        $users = $CardRankUserLog->allowField(true)->save($data);
                        $rec_id = $CardRankUserLog->id;

                        $marke = new \app\mobile\controller\Cardmarke();
                        if ($rank['reward_bonus'] > 0 && $rank['is_bonus'] =="Y"){
                            $bonus['card_id'] = $user['card_id'];
                            $bonus['code'] = $user['code'];
                            $bonus['openid'] = $user['openid'];
                            $bonus['add_bonus'] = $rank['reward_bonus'];
                            $bonus['name'] = '等级奖励';
                            $bonus['outerstr'] = '等级奖励';
                            $resbonus = $marke->varybonus($bonus);
                        }else{
                            $resbonus = 0;
                        }
                        if ($rank['reward_balance'] > 0 && $rank['is_balance'] =="Y"){
                            $balance['card_id'] = $user['card_id'];
                            $balance['code'] = $user['code'];
                            $balance['openid'] = $user['openid'];
                            $balance['add_balance'] = $rank['reward_balance'];
                            $balance['name'] = '等级奖励';
                            $balance['type'] = '3';
                            $balance['balance'] = $user['balance'] + $rank['reward_balance'];
                            $balance['outerstr'] = '等级奖励';
                            $resbalance = $marke->varybanlance($balance);
                        }else{
                            $resbalance = 0;
                        }
                        if ($rank['zs_card_id_all'] !== '' && $rank['is_cards'] =="Y"){
                            $cards['card_id'] = $user['card_id'];
                            $cards['remark'] = $rank['live_title'];
                            $cards['zs_card_info'] = $rank['zs_card_info'];
                            $cards['zs_card_id_all'] = $rank['zs_card_id_all'];
                            $cards['code'] = $user['code'];
                            $cards['openid'] = $user['openid'];
                            $cards['nickname'] = $user['nickname'];
                            $cards['rec_id'] = $rec_id;
                            $cards['top_mid'] = $user['top_mid'];
                            $cards['mid'] = $user['mid'];
                            $rescard = $marke->varycards($cards);
                        }else{
                            $rescard = 0;
                        }


                        if ($resbalance == 0 && $resbonus == 0 && $rescard == 0){
                            $ldata['rank_lock'] = $rank['live'];
                            $CardUserGet->save($ldata,$map);
                            $rarr['code'] = 0;
                            $rarr['message'] = '领取成功';
                        }else{
                            $rarr['code'] = 0;
                            $rarr['message'] = '领取失败';
                        }
                    }else{
                        $rarr['code'] = 9003;
                        $rarr['message'] = '无奖励';
                    }
                }else{
                    $rarr['code'] = 9002;
                    $rarr['message'] = '已领取';
                }
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '未达到';

            }
            return json($rarr);
        }
    }

    //等级判断
    private function is_rank_new($arr){
        $CardRank = new CardRank();
        $map['id'] = $arr['lid'];
        $rank = $CardRank->where($map)->find();
        if ($rank['growup'] <= $arr['user_growup']){
            $data = 0;      //达到
        }else{
            $data = 1;      //未达到
        }
        return $data;
    }


    //我的卡券  查询所有属于该openid的会员卡
    /*
     * $card_id
     */
    public function mecard()
    {
        $arr = request()->param();
        $this->_init();
        if (isset($arr['encrypt_code'])) {
            $this->getusercode($arr);
        }
        $appid = $this->getappid($arr['card_id']);
//        if (isset($arr['openid'])) {
//            Session::set($appid . '_openid');
//        }
//        var_dump($arr);
//        exit();




        $arr['openid'] = Session::get($appid . '_openid');
        $CardMember = new CardMember();
        $this->assign('card', $arr);
//        var_dump($arr);
        $is_mecard = $CardMember->where('card_id', $arr['card_id'])->value('is_mecard');
        if ($is_mecard == 1) {
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }

    }


    public function getmecard(){
        $param = request()->post();
//        return json($param);
        //我的会员卡
        $CardUserGet = new CardUserGet();
        //我的券
//        $maps['openid'] = Session::get($appid . '_openid');
        $maps['openid'] = $param['openid'];
        $maps['have'] = 1;
        $maps['is_out'] = 0;
        $maps['card_type'] = array('neq', 'MEMBER_CARD');
        $maps['statu'] = ['neq', 2];
        $cardlists = $CardUserGet->where($maps)->order('end_time asc')->paginate(5);
//            return json($cardlists);
        $cardcount = $CardUserGet->where($maps)->count();
        $cardlist = [];
        $i = 0;
        foreach ($cardlists as $k=>$v){
            $cards = filemegetcard($v['card_id'],$v['code'],$v['create_time']);

            if ($cards['result'] == 1) {
                $cardlist[$i]['card_id'] = $v['card_id'];
                $cardlist[$i]['card_type'] = getcardtype($v['card_type']);
                $cardlist[$i]['code'] = $v['code'];
                $cardlist[$i]['card_logo'] = $cards['cards']['logo_url'];
                $cardlist[$i]['card_title'] = $cards['cards']['title'];
                $cardlist[$i]['brand_name'] = $cards['cards']['brand_name'];
                $cardlist[$i]['out_time'] = date('Y-m-d h:i:s',$v['end_time']);
                $i = $i+1;
            }else{
                $CardUserGet->save(['is_out'=>1],['id'=>$v['id']]);
            }
        }
        if ($cardlist){
            $data['code'] = 0;
            $data['message'] = 'SUCCESS';
            $data['data'] = $cardlist;
            $data['count'] = $cardcount;
            $data['page_num'] = ceil($cardcount / 5);
            $data['page'] = $param['page'];
//                $data['sql'] = $CardUserGet->getLastSql();
        } else {
            $data['code'] = 0;
            $data['data'] = '';
            $data['message'] = 'error';
        }
        return json($data);
    }

    //适用门店
    /*
     * $card_id
     */
    public function storelist($card_id = '')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $CardMember = new CardMember();
            $Merchant = new Merchant();
            $top_mid = $CardMember->where('card_id', $card_id)->value('top_mid');
            $base_info = $CardMember->where('card_id', $card_id)->value('base_info');
            $base_info = json_decode($base_info, true);
            if ($base_info['use_all_locations'] == 'true') {
                $mab['top_mid'] = $top_mid;
            } else {
                $mapid = $base_info['location_id_list'];
                $mab['mapid'] = ['in', $mapid];
            }
            $storelist = $Merchant->where($mab)->select();
            $this->assign('list', $storelist);
            $is_locations = $CardMember->where('card_id', $card_id)->value('is_locations');
            if ($is_locations == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //门店详情
    /*
     * 门店id
     * $id
     */
    public function storeinfo($id)
    {
        $Merchant = new Merchant();
        $MerchantContent = new MerchantContent();
        $map['id'] = $id;
        $info = $Merchant->where($map)->find();
        $info['phone'] = $MerchantContent->where('mid',$id)->value('tel');
        $this->assign('info', $info);
        $share['wxjssdk'] = $this->getwxjssdk($id);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $this->assign('share',$share);
        return $this->fetch();
    }

    //会员卡详情
    /*
     * $card_id
     *
     */
    public function cardinfo($card_id ='')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $CardMember = new CardMember();
            $card = $CardMember->where('card_id', $card_id)->find();
            $card['base_info'] = json_decode($card['base_info'], true);
            $card['bonus_rule'] = json_decode($card['bonus_rule'], true);
            $this->assign('card', $card);
            $is_card_info = $CardMember->where('card_id', $card_id)->value('is_card_info');
            if ($is_card_info == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //修改资料
    /*
     * $card_id
     *
     */
    public function userinfo($card_id = '')
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $info = $this->getuserinfo($arr);
        if ($info) {
            $map['card_id'] = $card_id;
            $map['openid'] = Session::get($appid.'_openid');
            $CardUserGet = new CardUserGet();
            $info = $CardUserGet->where($map)->find();
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            //END
            $this->assign('info', $info);

            $CardMember = new CardMember();
            $card = $CardMember->where('card_id', $card_id)->field('is_edit_user,syn_is_exist')->find();

            $this->assign('card',$card);
            if ($card['is_edit_user'] == 1) {
                return $this->fetch();
            } else {
                return $this->fetch('off');
            }
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //修改会员资料
    /*
     * $card_id
     *
     */
    public function editinfo()
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $info = $this->getuserinfo($arr);
        if ($info) {
            $map['card_id'] = $arr['card_id'];
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($arr['card_id']);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share',$share);
            //END
            $this->assign('info', $info);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);
        }
    }

    //修改处理
    /*
     * $data['id'] $data['card_id']
     * POST 修改数据
     *
     */
    public function editinfohand(){
        if (Request()->isPost()){
            $data = request()->post();
            $map['id'] = $data['id'];
            $CardUserGet = new CardUserGet();
            $res = $CardUserGet->allowField(true)->save($data,$map);
            if ($res){
                $this->success('修改成功！',url('carduser/editinfo', ['card_id' => $data['card_id']]));
//                $rarr['code'] = 0;
//                $rarr['message'] = '修改成功！';
            }else{
                $this->error('修改失败！',url('carduser/editinfo', ['card_id' => $data['card_id']]));
//                $rarr['code'] = 9001;
//                $rarr['message'] = '修改失败';
            }
        }
    }

    //我的订单
    /*
     * $card_id
     *
     */
    public function orderme($card_id)
    {
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($card_id);
        $info = $this->getuserinfo($arr);
        if ($info) {
            $mab['openid'] = Session::get($appid.'_openid');
            $mab['card_id'] = $card_id;
            $CardOrder = new CardOrder();
            $list = $CardOrder->where($mab)->order('id desc')->select();
            $card['card_id'] = $card_id;
            $this->assign('list', $list);
            $this->assign('card',$card);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    //订单详情
    /*
     * 订单id 会员卡$card_id
     *
     * $id $card_id
     */
    public function orderinfo(){
        $arr = request()->param();
        //解密code 获取用户信息
        if (isset($arr['encrypt_code'])){
            $this->getusercode($arr);
        }
        //获取授权
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $info = $this->getuserinfo($arr);
        if ($info) {
            $mab['openid'] = Session::get($appid.'_openid');
            $mab['card_id'] = $arr['card_id'];
            $mab['id'] = $arr['id'];
            $CardGoods = new CardGoods();
            $CardOrder = new CardOrder();
            $order = $CardOrder->where($mab)->find();
            $goods = $CardGoods->where('id',$order['gid'])->find();
            $this->assign('goods',$goods);
            $this->assign('order', $order);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);
        }
    }

    //功能开关   暂时弃用
    /*
     *  $arr['openid'] / $arr['card_id'] / $arr['is_dedu_cards']
     *
     */
    public function disetup(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $map['openid'] = $arr['openid'];
            $map['card_id'] = $arr['card_id'];
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $data['is_dedu_cards'] = $arr['is_dedu_cards'];
            $res = $CardUserGet->allowField('is_dedu_cards')->update($data,$map);
            if ($res){
                $rass['code'] = 0;
                $rass['message'] = '修改成功';
            }else{
                $rass['code'] = 9001;
                $rass['message'] = '修改失败';
            }
            return json($rass);
        }else{
            $this->_init();
            $arr = request()->param();
            $appid = $this->getappid($arr['card_id']);
            $map['openid'] = Session::get($appid.'_openid');
            $map['card_id'] = $arr['card_id'];
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $CardUserGet = new CardUserGet();
            $info = $CardUserGet->where($map)->find();
            if ($info) {                                                                //会员信息
                $card['card_id'] = $arr['card_id'];
                $this->assign('info', $info);
                $this->assign('card',$card);
                return $this->fetch();
            } else {
                $this->redirect('Carduser/weboff', ['card_id' => $arr['card_id']]);        //关闭
            }
        }
    }

    //关闭页面 (jssdk 实现)
    /*
     * $card_id
     *
     */
    public function weboff($card_id)
    {
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($card_id);
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        return $this->fetch();
    }

    //打开卡
    /*
     * $card_id /
     *
     */
    public function opencard()
    {
        $this->tzbizopencard(request()->param());
        $this->_init();

        $card_id = request()->param('card_id');
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid.'_openid');
        $CradUserGet = new CardUserGet();
        $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid, 'have' => '1', 'statu' => 0])->find();
        if ($info) {
            $card['card_id'] = $card_id;
            $card['code'] = $info['code'];
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            $options = $this->options($card_id);
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->getJsSign($url);
            //输出内容
            $card['jssdk']['debug'] = true;
            $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//            var_dump($url);
//                $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
            $card['card']['cardId'] = $card_id;
            $card['card']['code'] = $info['code'];
            $this->assign('jssdk', $jssdk);
            $this->assign('card', $card);
            return $this->fetch();
        } else {
            $data['card_id'] = $card_id;
            $data['openid'] = $openid;
            $this->redirect(url('carduser/addcard', $data));
        }
    }

    //检查一键开卡链接并跳转
    public function tzbizopencard($param){
        $CardQrcode = new CardQrcode();
        $map['card_id'] = $param['card_id'];
        $map['outer_str'] = $param['mid'];
        $map['type'] = 1;
//        var_dump($map);
//        exit();
        $info = $CardQrcode->where($map)->find();
//        if ($info){
//            if (!empty($info['url_mobile'])) {
//                $this->redirect($info['url_mobile']);
//            }
//        }else{
//            unset($map['outer_str']);
//            $infos = $CardQrcode->where($map)->find();
//            if ($infos){
//                if (!empty($infos['url_mobile'])) {
//                    $this->redirect($infos['url_mobile']);
//                }
//            }
//        }
    }

    //发放卡
    /*
     * $arr['openid'] / $arr['card_id']
     *
     *
     */
    public function addcard()
    {
//        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['card_id'])) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = $arr['openid'];
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //发放卡
    /*
     *
     *
     */
    public function addcardmicro()
    {
        $this->_init();

        $card_id = request()->param('card_id');
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid.'_openid');
        if (isset($openid) && isset($card_id)) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($card_id);
            //发放
            $arrs['card_id'] = $card_id;
            $arrs['openid'] = $openid;
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }


    //AJax打开卡
    /*
     * $arr['card_id'] , $arr['url']
     *
     */
    public function getopencard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $card_id = $arr['card_id'];
            $appid = $this->getappid($card_id);
            $openid = Session::get($appid.'_openid');
            $CradUserGet = new CardUserGet();
            $map['openid'] = $openid;
            $map['card_id'] = $card_id;
            $map['code'] = $arr['cardcode'];
            $map['have'] = 1;
            $map['statu'] = 0;
            $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid,'code' =>  $arr['cardcode'], 'have' => '1', 'statu' => 0])->find();

            if ($info) {
                $url = $arr['url'];
                $options = $this->options($card_id);
                $weObj = new Wxobjopen($options);

                $jssdk = $weObj->getJsSign($url);
                //输出内容
                $card['jssdk']['debug'] = true;
                $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//                $card['jssdk']['url'] = $jssdk['url'];
                $card['jssdk']['timestamp'] = $jssdk['timestamp'];
                $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
                $card['jssdk']['signature'] = $jssdk['signature'];
                $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
                $card['card']['cardId'] = $card_id;
                $card['card']['code'] = $info['code'];
                return json($card);
            } else {
                $data['code'] =  9001;
                $data['msg'] = '没有此卡，请先领取！';
                return json($data);
            }
        }
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $appid = $this->getappid($arr['card_id']);
            $arrs['openid'] = Session::get($appid.'_openid');
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->get_card_JsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = false;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['penCard','addCard'];
            return json($card);
        }
    }

    //发放卡列表
    /*
     * $arr['openid'] / $arr['give'] /
     *
     */
    public function addcardlist()
    {
        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['give'])) {
            $appid = $this->getappid($arr['card_id']);
            if ($arr['openid'] == Session::get($appid.'_openid')) {
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('zs_card_id');
                $cardlist = explode(',', $card_id);
                foreach ($cardlist as $k => $v) {
                    if (filteroffcard($v) == true) {
                        $options = $this->options($v);
                        $arrs['card_id'] = $v;
                        $arrs['openid'] = $arr['openid'];
                        $card[$k] = $this->putlist($arrs);
                    }
                }
                if(isset($options)){
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch();
                }
                else{
                    $this->error("该卡券已过期");
                }
            }else{
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('card_id');
                $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
            }
        }
    }

    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr){
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr);
        return $res;
    }

    //投放卡
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = 'CardCenter';
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr,$outer_str);
        return $res;

    }

    //获取该门店所属商户的所有下属门店
    /*
     * $mid
     */
    private function getmidlist($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id',$mid)->value('top_mid');
        $midlist = $Merchant->where(['top_mid' => $top_mid])->field('id')->select();
        $smid=[];
        foreach ($midlist as $k => $v) {
            $smid[] = $v['id'];
        }
        $mids = implode(',', $smid);
        return $mids;
    }

    /* 获取创建该卡券的门店id
     *
     * $card_id
     *
     */
//    private function getmid($card_id)
//    {
//        $CardMember = new CardMember();
//        $CardGeneral = new CardGeneral();
//        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
//        if (empty($top_mid)) {
//            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
//            return $top_mid;
//        } else {
//            return $top_mid;
//        }
//    }

    //分享jssdk
    /*
     * $card_id
     *
     */
    private function getwxjssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->option($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'openLocation',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }


    //分享jssdk
    /*
     * $card_id
     * 
     */
    private function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }
    public function test(){
        echo request()->domain();
        exit();
        $s=getgivecardnew('[{"zs_card_id":"pCVCLv0Z2UNmnrRcoC2bamHpj0EY","zs_no":"2"}]',0);
   var_dump($s);
    }


}
